<?php
require_once "site_config.php";
require_once "ra_global.php";
// 红包积分抽奖
$method = $_GET['method'];
if($method == "getRedPocket"){
    $userId = $_GET['userid'];

    echo getRedPocket($db, $userId);
}
// 红包浮层提示check
else if ($method == "checkpopup") {
    $userId = $_GET['userid'];

    echo checkPopup($db, $userId);
}
else if ($method == "checkfestival") {
    $userId = $_GET['userid'];

    echo checkfestival($db, $userId);
}

function getRedPocket($db, $userId) {
    $result = array();

    // 只有店长和店员可以兑换红包
    $user = $db->ig2_want('mae_user','id='.$userId.' AND role_type in (1,2) AND is_delete=0');
    if (!$user) {
        $result['errcode'] = 1;
        $result['errmsg'] = '对不起，只有店长和机修工才能兑换红包';
        return json_encode($result);
    }

    $now = time();
    $redPocketActivity = $db->ig2_want('mae_red_pocket_activity','status=1 AND starttime <= '.$now.' AND endtime >= '.$now);
    // 如果没有开启的红包活动，报错;
    if (!$redPocketActivity) {
        $result['errcode'] = 1;
        $result['errmsg'] = '待活动开始后，通过个人中心页面提示';
        return json_encode($result);
    }

    // 当前员工是否在活动组内
    $groupSql = " SELECT g.* FROM mae_group g";
    $groupSql .= " INNER JOIN mae_rel_red_pocket_activity_group mrrpag ON mrrpag.groupid = g.id";
    $groupSql .= " INNER JOIN mae_red_pocket_activity mrpa ON mrpa.id = mrrpag.activityid";
    $groupSql .= " INNER JOIN mae_rel_group_shop mrgs ON mrgs.groupid = g.id";
    $groupSql .= " INNER JOIN mae_shop s ON s.id = mrgs.shopid AND s.status = 1";
    $groupSql .= " INNER JOIN mae_role r ON r.shop_id = s.id AND r.is_delete = 0";
    $groupSql .= " INNER JOIN mae_user u ON u.id = r.uid AND u.is_delete = 0";
    $groupSql .= " WHERE u.id = ".$userId." AND mrpa.id = ".$redPocketActivity['id'];

    $group = $db->ig2_query_select($groupSql);

    if (!$group) {
        $result['errcode'] = 1;
        $result['errmsg'] = '待活动开始后，通过个人中心页面提示';
        return json_encode($result);
    }

    // 如果已兑换积分大于等于可兑换积分总数，则不能继续兑换
    if ($redPocketActivity['usedscore'] >= $redPocketActivity['totalscore']) {
        $result['errcode'] = 1;
        $result['errmsg'] = '对不起，已兑换的积分已达活动上限';
        return json_encode($result);
    }

    // 如果相同的兑换活动，该用户已经兑换过，则不能再次兑换
    $exchangeLog = $db->ig2_want('mae_red_pocket_exchange_log','userid='.$userId.' AND activityid='.$redPocketActivity['id']);
    if ($exchangeLog) {
        $result['errcode'] = 1;
        $result['errmsg'] = '对不起，您已经领取过该活动红包';
        return json_encode($result);
    }

    // 根据活动的概率设定，确定红包积分范围
    $score = 0;
    $randnum = rand(1, 100);

    // 1-5分
    if ($randnum <= $redPocketActivity['range1probability']) {
        $score = getScoreBetween(1, 5);
    }
    // 6-10分
    else if ($randnum > $redPocketActivity['range1probability'] && $randnum <= $redPocketActivity['range1probability'] + $redPocketActivity['range2probability']) {
        $score = getScoreBetween(6, 10);
    }
    // 11-15分
    else if ($randnum > $redPocketActivity['range1probability'] + $redPocketActivity['range2probability']
        && $randnum <= $redPocketActivity['range1probability'] + $redPocketActivity['range2probability'] + $redPocketActivity['range3probability']) {
        $score = getScoreBetween(11, 15);
    }
    // 16-20分
    else {
        $score = getScoreBetween(16, 20);
    }

    // 如果兑换的积分大于总积分与所有已兑换的积分的差，则使用积分的差作为最终获得积分
    if ($score > $redPocketActivity['totalscore'] - $redPocketActivity['usedscore']) {
        $score = $redPocketActivity['totalscore'] - $redPocketActivity['usedscore'];
    }

    $db->ig2_query('BEGIN');

    $success = true;
    $actionResult = false;
    // 记录红包领取日志
    $actionResult = $db->ig2_query("insert into mae_red_pocket_exchange_log(`userid`,`activityid`,`activityname`,`exchangescore`,`createtime`)
                      VALUES (".$userId.", ".$redPocketActivity['id'].", '".str_replace ( "'", "''",$redPocketActivity['activityname'])."', ".$score.", ".time().");");
    $success=$success && $actionResult?true:false;

    // 更新已领红包积分
    if ($success) {
        $actionResult=$db->ig2_query("update mae_red_pocket_activity set usedscore=usedscore+".$score." WHERE id=".$redPocketActivity['id']);
    }
    $success=$success && $actionResult?true:false;

    // 更新个人积分
    if ($success) {
        if ($user['role_type'] == 2) {
            $actionResult = $db->ig2_query("update mae_user set score=score+".$score." where id=".$userId);
        } else {
            $actionResult = $db->ig2_query("update mae_shop set quadratic=quadratic+".$score." where admin_id = ".$userId);
        }
    }
    $success=$success && $actionResult?true:false;

    if ($success) {
        $db->ig2_query('COMMIT');
        $result['errcode'] = 0;
        $result['score'] = $score;
    } else {
        $db->ig2_query('ROLLBACK');
        $result['errcode'] = 1;
        $result['errmsg'] = '服务器异常';
    }
    return json_encode($result);
}

// 返回指定范围随机数
function getScoreBetween($start, $end) {
    return rand($start, $end);
}

// 红包浮层提示check
function checkPopup($db, $userId) {
    $now = time();
    $result = array();

    $redPocketActivity = $db->ig2_want('mae_red_pocket_activity','status=1 AND starttime <= '.$now.' AND endtime >= '.$now);
    // 有红包活动的时候才会弹浮层
    if ($redPocketActivity) {
        $groupSql = " SELECT g.*, mrpa.id as activityid FROM mae_group g";
        $groupSql .= " INNER JOIN mae_rel_red_pocket_activity_group mrrpag ON mrrpag.groupid = g.id";
        $groupSql .= " INNER JOIN mae_red_pocket_activity mrpa ON mrpa.id = mrrpag.activityid";
        $groupSql .= " INNER JOIN mae_rel_group_shop mrgs ON mrgs.groupid = g.id";
        $groupSql .= " INNER JOIN mae_shop s ON s.id = mrgs.shopid AND s.status = 1";
        $groupSql .= " INNER JOIN mae_role r ON r.shop_id = s.id AND r.is_delete = 0";
        $groupSql .= " INNER JOIN mae_user u ON u.id = r.uid AND u.is_delete = 0";
        $groupSql .= " WHERE u.id = ".$userId." AND mrpa.id = ".$redPocketActivity['id'];
        $group = $db->ig2_query_select($groupSql);

        // 当前员工在活动组内的时候才弹浮层
        if ($group) {
            // 已经提醒过的不再提醒
            $log = $db->ig2_want('mae_red_pocket_activity_popup_log', 'activityid = '.$redPocketActivity['id'].' AND userid = '.$userId);
            if (!$log) {
                $db->ig2_query('INSERT INTO mae_red_pocket_activity_popup_log (activityid, userid, createtime) VALUES ('.$redPocketActivity['id'].', '.$userId.', '.$now.')');
                $result['status'] = 1;
            } else {
                $result['status'] = 0;
            }
        } else {
            $result['status'] = 0;
        }
    } else {
        $result['status'] = 0;
    }
	

    return json_encode($result);
}
?>